<?php

namespace app\index\controller\user;

use app\common\model\admin\ApplyModel;
use app\index\controller\BaseIndex;
use think\facade\Validate;

/**
 * 申请入驻
 *
 * @Description
 * @package app\index\controller\user
 * @author wangqinghui
 * @date 2024-10-30 16:45
 */
class ApplyShop extends BaseIndex
{
    // 是否校验登录
    protected $check_login = true;

    /**
     * 申请入驻
     *
     * @Description
     * @author wangqinghui
     * @date 2024-10-30 16:44
     * @return void
     */
    public function index()
    {
        $this->title = lang('申请开店');
        if($this->request->isPost()){
            $post_data = $this->request->post();
            $rule = [
                'account_name|公司名称'     =>      'require|max:50',
                'login_account|账号'        =>      'require|length:4,50',
                'password|密码'             =>      'require|length:6,25|max:255',
            ];
            $valid = Validate::rule($rule);
            if(!$valid->check($post_data)){
                $this->error($valid->getError());
            }
            // 校验用户是否已经申请过
            $map = [
                ['index_user_id',    '=',   $this->user_id],
            ];
            $apply_info = ApplyModel::mk()->field('id,index_user_id,status')->order('id desc')->where($map)->find();
            if(!empty($apply_info)){
                if($apply_info['status'] == ApplyModel::STATUS_APPLY){
                    $this->error('您已经申请过了,请耐心等待审核');
                }elseif($apply_info['status'] == ApplyModel::STATUS_AGREE){
                    $this->error('您的申请已经通过了,请登录后台进行操作');
                }
            }
            // 校验公司和账号是否已经注册过
            $map1 = [
                ['account_name',     '=',   $post_data['account_name']],
                ['status',           '=',   ApplyModel::STATUS_AGREE],
            ];
            $map2 = [
                ['login_account',    '=',   $post_data['login_account']],
                ['status',           '=',   ApplyModel::STATUS_AGREE],
            ];
            $exist_info = ApplyModel::mk()->field('id')->whereOr([$map1, $map2])->find();
            if(!empty($exist_info)){
                $this->error('公司名称或账号已存在,请重新申请');
            }
            $add_data = [
                'index_user_id'    =>  $this->user_id,
                'account_id'      =>   $this->userInfo['job_place'] ?? 0,
                'account_name'     =>  $post_data['account_name'],
                'login_account'    =>  $post_data['login_account'],
                'password'         =>  $post_data['password'],
                'status'           =>  ApplyModel::STATUS_APPLY,
            ];
            $apply_id = ApplyModel::mk()->insertGetId($add_data);
            if(empty($apply_id) || ($apply_id <= 0)){
                $this->error('申请失败,请重新申请');
            }
            $this->success('申请成功,请耐心等待审核');
        }else{
            $title = lang('申请入驻跨境电商运营系统平台');
            $this->fetch('index', ['main_title' => $title]);
        }
    }
}